<template>
  <!-- #ifndef H5 -->
  <u-navbar title="预约发货" fixed border leftIcon="" leftText=""></u-navbar>
  <!-- #endif -->
  <!-- #ifdef H5 -->
  <u-navbar title="预约发货" fixed border @leftClick="navigateBack" @rightClick="navigateHome">
    <template #right>
      <u-icon name="home" size="24"></u-icon>
    </template>
  </u-navbar>
  <!-- #endif -->
  <view class="page_wrap_container" :style="{ paddingTop: NavBarHeight + 'px' }">
    <scroll-view :style="{ height: windowHeight + 'px' }" scroll-y enable-flex :show-scrollbar="false"
      class="purchase_page_list" v-if="(pageDetails?.list && pageDetails?.list?.length > 0)">
      <view class="list_item">
        <view class="list_item_header">
          <view class="lih_title">{{ pageDetails?.list?.[0]?.supplierName }}</view>
        </view>
        <view class="list_item_img_box list_item_img_box_spec">
          <up-checkbox-group placement="column" v-model="modalData.selected" @change="onSelectChange">
            <up-checkbox v-for="it in pageDetails?.list" :key="it.id" :name="it.id"
              :disabled="it.orderQty - it.scheduledQty <= 0">
              <template #label class="liib_item_slot_wrap">
                <view class="liib_item">
                  <view class="liibi_main">
                    <view class="lm_imgbox">
                      <image :src="it.imageUrl" alt="" />
                    </view>
                    <view class="lm_textbox">
                      <view class="liibi_title_box">
                        <view class="left_main_title text_ellipsis">{{ it.productName || '-' }}</view>
                        <view class="price_num">待预约数量：{{ it.orderQty - it.scheduledQty >= 0 ? it.orderQty
    - it.scheduledQty : 0 }}</view>
                      </view>
                      <view class="subtitle">款式编码：{{ it.spuCode || '-' }}</view>
                      <view class="subtitle">商品条码：{{ it.skuCode || '-' }}</view>
                      <view class="subtitle liibi_btm">
                        <view>{{ it.colorDetailName || '-' }}；{{ it.commoditySize }}</view>
                      </view>
                      <view class="number_box_step"><up-number-box integer v-model="it.scheduleQty"
                          :disabled="!modalData.selected.includes(it.id)"
                          :max="it.orderQty - it.scheduledQty >= 0 ? it.orderQty - it.scheduledQty : 0"></up-number-box>
                      </view>
                    </view>
                  </view>
                </view>
              </template>
            </up-checkbox>
          </up-checkbox-group>
          <view class="actions_box" @click.stop="selectAll">
            <view class="ab_btn">{{ isSelectAll ? "全不选" : "全选" }}</view>
          </view>
        </view>
      </view>
      <view class="form_wrap">
        <up-form labelAlign="right" :model="modalData" labelWidth="130">
          <up-form-item label="预约发货时间：" prop="modalData.scheduleDeliveryTime">
            <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowDatePicker"
              :title="modalData.scheduleDeliveryTime" :isLink="true" arrow-direction="down" :border="false"></up-cell>
          </up-form-item>
        </up-form>
      </view>
      <view class="fixed_btutton"><up-button type="primary" color="#42bac3" text="确定" shape="circle"
          @click="handleSave"></up-button></view>
      <view :style="{ height: '50px' }"></view>
    </scroll-view>
    <view class="empty_wrap" :style="{ height: windowHeight + 'px' }" v-else>
      <up-empty mode="order" text="暂无数据～">
      </up-empty>
    </view>
    <up-datetime-picker ref="datetimePickerRef" closeOnClickOverlay :show="datePickerShow"
      v-model="modalData.scheduleDeliveryTime" mode="datetime" :formatter="formatter" @confirm="datePickerConfirm"
      @cancel="datePickerClose" @close="datePickerClose"></up-datetime-picker>
  </view>

</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import HTTP from "@/utils/http"
import dayjs from "dayjs"
import { reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import useScreenSize from "@/hooks/useScreenSize";
const { windowHeight, NavBarHeight, isIphoneX } = useScreenSize()
const navigateBack = () => {
  uni.navigateBack()
}
const navigateHome = () => {
  uni.switchTab({ url: "/pages/index/index" })
}
//获取页面 purchaseOrderCode
let purchaseOrderCode: string
onLoad((options: any) => {
  purchaseOrderCode = options.purchaseOrderCode || ""
})
let pageDetails = ref<{ list: any[] }>({
  list: []
})
const modalData = reactive<{ scheduleDeliveryTime: string, selected: (string | number)[] }>({
  scheduleDeliveryTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  selected: []
})
const isSelectAll = computed(() => {
  const excludeThanZero = pageDetails.value?.list?.filter((it: any) => it.orderQty - it.scheduledQty > 0)
  return (excludeThanZero.length > 0 && modalData.selected.length > 0 && excludeThanZero.length === modalData.selected.length)
})
const selectAll = () => {
  if (isSelectAll.value) {
    modalData.selected = []
    pageDetails.value.list = pageDetails?.value?.list?.map((item: any) => {
      return {
        ...item,
        scheduleQty: 1
      }
    })
  } else {
    const allIds = Array.isArray(pageDetails.value?.list) && pageDetails.value?.list?.filter(it => it.orderQty - it.scheduledQty > 0).map((item: any) => item.id)
    modalData.selected = allIds || []
    lastSelected.value = allIds || []
  }
}
const lastSelected = ref<string[]>([])
const onSelectChange = (currentSelected: string[]) => {
  if (lastSelected.value.length > currentSelected.length) {
    const delId = lastSelected.value?.filter(item => !currentSelected.includes(item))
    const index = pageDetails?.value?.list?.findIndex((item: any) => item.id == delId)
    if (index >= 0) {
      pageDetails.value.list[index]["scheduleQty"] = 1
    }
  }
  lastSelected.value = currentSelected
}
//DatePicker
const datetimePickerRef = ref<any>(null);
const formatter = (type: string, value: string) => {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  if (type === 'hour') {
    return `${value}时`;
  }
  if (type === 'minute') {
    return `${value}分`;
  }
  return value;
};
const datePickerShow = ref(false)
const handleShowDatePicker = () => {
  datePickerShow.value = true
}
const datePickerConfirm = (event: any) => {
  datePickerShow.value = false
  modalData.scheduleDeliveryTime = dayjs(event.value).format("YYYY-MM-DD HH:mm:ss")
}
const datePickerClose = () => {
  datePickerShow.value = false
}
const handleSave = () => {
  if (modalData.selected?.length === 0) {
    uni.showToast({
      icon: "none",
      title: "请选择商品"
    })
    return
  }
  const paramsArr = pageDetails.value.list?.filter((item: any) => modalData.selected.includes(item.id))
  console.log(paramsArr, 'params');
  const detailDTOList = paramsArr.map((item: any) => {
    return {
      orderQty: item.orderQty,
      purchaseOrderCode: item.purchaseOrderCode,
      scheduleQty: item.scheduleQty,
      skuCode: item.skuCode,
      spuCode: item.spuCode
    }
  })
  HTTP.POST({
    url: "sop/sop/reserveInvoice/create",
    isJson: true,
    data: { scheduleDeliveryTime: modalData.scheduleDeliveryTime, detailDTOList },
    success: (res: any) => {
      if (res.code == 200) {
        uni.showToast({
          title: '操作成功',
          icon: 'none',
        })
        uni.navigateBack()
      }
    },
    complete: () => {

    }
  })
}
//列表数据
onMounted(() => {
  datetimePickerRef.value && datetimePickerRef.value?.setFormatter(formatter);
  getListDataDetail()
})
const getListDataDetail = async () => {
  const params = {
    current: 1,
    size: 999,
    purchaseOrderCode
  }
  HTTP.POST({
    url: "sop/sop/purchase/order/commodity/queryReserveInvoicePurchaseDetail",
    isJson: true,
    data: params,
    success: (res: any) => {
      if (res.code == 200) {
        pageDetails.value = res.data
        pageDetails.value.list = res.data?.list?.map((item: any) => {
          return {
            ...item,
            scheduleQty: 1
          }
        }) || []
      }
    }
  })
}
</script>
<style lang="scss" scoped>
.fixed_btutton {
  width: 100%;
  margin: 24rpx 0;
  padding: 0 24rpx;
}

.page_wrap_container {
  display: flex;
  flex-direction: column;

  .purchase_page_list {

    .has_data_text {
      color: #aaa;
      text-align: center;
    }

    .list_item {
      margin: 24rpx 24rpx 0;
      box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.08);
      background-color: #fff;
      display: flex;
      flex-direction: column;
      margin-bottom: 24rpx;
      border-radius: 18rpx;
      overflow: hidden;

      .list_item_header {
        padding: 0 20rpx;
        height: 80rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .lih_title {
          flex: 1;
          font-weight: 500;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          font-size: 34rpx;
        }

        .lih_tag {
          flex-shrink: 0;
        }
      }

      .list_item_img_box {
        padding: 0 20rpx;

        .liib_item_slot_wrap {
          width: 100%;
        }

        .liib_item {
          display: flex;
          flex-direction: column;
          margin-bottom: 12rpx;
          flex: 1;

          .liibi_main {
            display: flex;

            .lm_imgbox {
              width: 120rpx;
              height: 120rpx;
              margin-top: 8rpx;
              border-radius: 6rpx;
              overflow: hidden;
              flex-shrink: 0;

              image {
                width: 100%;
                height: 100%;
              }
            }

            .lm_textbox {
              flex: 1;
              padding-left: 12rpx;
              font-size: 28rpx;

              .liibi_title_box {
                font-size: 30rpx;
                color: #333;
                display: flex;
                // align-items: center;
                justify-content: space-between;

                .left_main_title {
                  max-width: 400rpx;
                  font-weight: 500;
                }

                .price_num {
                  font-weight: normal;
                  color: #666;
                  font-size: 26rpx;
                }
              }

              .subtitle {
                color: #888;
              }

              .number_box_step {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                margin-top: -20rpx;
              }

              .liibi_btm {
                display: flex;
                align-items: center;
                justify-content: space-between
              }

            }
          }
        }
      }

      .actions_box {
        border-top: 1px solid #f1f1f1;
        padding: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .ab_btn {
          font-size: 30rpx;
          padding: 10rpx;
          color: $uni-color-primary;
        }
      }
    }

    .look_more {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      font-size: 28rpx;
      color: $uni-color-primary;
      margin-right: 4rpx;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0rpx;
      padding-top: 100rpx;
    }
  }

  .empty_wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

.form_wrap {
  background-color: #fff;
  margin: 0 24rpx;
  box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.08);
  width: 702rpx;
  padding: 24rpx 30rpx;
  border-radius: 18rpx;
}

.pop_actions {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .reset_btn {
    color: #888;
    padding: 12rpx;
  }

  .confirm_btn {
    color: $uni-color-primary;
    padding: 12rpx;
  }

  .status_item {
    .status_item_title {
      padding: 30rpx 0;
      font-size: 36rpx;
      font-weight: 400;
      color: #333;
    }

    .status_item_btns_box {
      display: flex;
      flex-wrap: wrap;
      gap: 18rpx;

      .status_item_btn {
        border: 1px solid #ddd;
        padding: 10rpx 20rpx;
        color: #666;
      }

      .status_item_btn_active {
        border: 1px solid $uni-color-primary;
        background-color: $uni-color-primary;
        color: #fff;
      }
    }
  }
}
</style>
<style>
.list_item_img_box_spec .u-checkbox__icon-wrap {
  margin-top: -22px !important;
}
</style>